<template>
    <van-address-list v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit"
        @select="selectHandle" />
</template>

<script>
import { getAddressList } from "../../api/index.js"
export default {
    name: "AddressList",

    props: [],
    data() {
        return {
            list: [], // 地址列表的数据源
            chosenAddressId: ""
        };
    },
    async created() {
        await this.getData();

        let res = this.list.filter(item => item.isDefault == true)
        this.chosenAddressId = res[0]?.id
    },
    methods: {
        // 点击新增地址
        onAdd() {
            this.$router.push("/addressEdit");
        },
        // 点击编辑地址
        onEdit(item, index) {
            this.$router.push("/addressEdit?addressId=" + item.id);
        },
        // 获取地址数据列表
        async getData() {
            await getAddressList().then(res => {
                this.list = res.data.map(item => {
                    return {
                        id: item.addressId + "",
                        name: item.userName,
                        tel: item.userPhone,
                        address:
                            item.provinceName +
                            item.cityName +
                            item.regionName +
                            item.detailAddress,
                        isDefault: item.defaultFlag ? true : false,
                    }
                })

            })
        },
        // 点击某个地址 
        selectHandle(item, index) {
            console.log("item:", item);
            this.$router.push({
                path: "/create-order",
                query: {
                    addressId: item.id,
                }
            });
        }
    },
    // watch: {
    //     chosenAddressId(val) {
    //         console.log("val:", val);
    //         // 跳到生成订单页面
    //         this.$router.push({
    //             path: "/create-order",
    //             query: {
    //                 addressId: val,
    //             }
    //         });
    //     }
    // }
};
</script>

<style lang="less" scoped>

</style>